package _21_多线程._1114_按序打印;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

public class _1114_按序打印_LockSupport {

    private final Map<String, Thread> map = new ConcurrentHashMap<>();

    volatile int num;

    public _1114_按序打印_LockSupport() {
    }

    public void first(Runnable printFirst) throws InterruptedException {
        printFirst.run();
        num = 1;
        LockSupport.unpark(map.get("second"));
    }

    public void second(Runnable printSecond) throws InterruptedException {
        if (num != 1) {
            map.put("second", Thread.currentThread());
            LockSupport.park();
        }
        printSecond.run();
        num = 2;
        LockSupport.unpark(map.get("three"));
    }

    public void third(Runnable printThird) throws InterruptedException {
        if (num != 2) {
            map.put("three", Thread.currentThread());
            LockSupport.park();
        }
        printThird.run();
    }

}
